#include "ShadowMap.h"
#include "RenderItemManager.h"
#include "Game.h"

ShadowMap::ShadowMap()
{

}

ShadowMap::ShadowMap(const ShadowMap&)
{

}

ShadowMap::~ShadowMap()
{

}

void ShadowMap::Initialize()
{
	mWidth = 1024;
	mHeight = 1024;

	mCDirect3D = CDirect3D::Instance();
	mDeviceContext = mCDirect3D->GetDeviceContext();
	mDevice = mCDirect3D->GetDevice();
	CreateTexture();
	mCDirect3D->CreateDepthBuffer(mWidth, mHeight, &mTextureDepthBuffer, &mStencilViewDepthBuffer);


	D3D11_RENDER_TARGET_VIEW_DESC renderTargetDesc;
	renderTargetDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
	renderTargetDesc.ViewDimension = D3D11_RTV_DIMENSION::D3D11_RTV_DIMENSION_TEXTURE2D;
	renderTargetDesc.Texture2D.MipSlice = 0;

	HRESULT result;
	result = mDevice->CreateRenderTargetView(mTexture, &renderTargetDesc, &mRenderTargetView);

	if(FAILED(result))
	{
		return;
	}

	D3D11_SHADER_RESOURCE_VIEW_DESC  shaderResourceViewDesc;
	// Setup the description of the shader resource view.
	shaderResourceViewDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
	shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
	shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
	shaderResourceViewDesc.Texture2D.MipLevels = 1;

	result = mDevice->CreateShaderResourceView(mTexture,&shaderResourceViewDesc,&mTextureRessource);


	mViewportShadow.Width = (float)mWidth;
	mViewportShadow.Height = (float)mHeight;
	mViewportShadow.MinDepth = 0.0f;
	mViewportShadow.MaxDepth = 1.0f;
	mViewportShadow.TopLeftX = 0.0f;
	mViewportShadow.TopLeftY = 0.0f;
}



void ShadowMap::Update()
{

}

void ShadowMap::Render(XMFLOAT4X4* pViewMatrix, XMFLOAT4X4* pProjectionMatrix)
{
	float color[4];

	// Setup the color to clear the buffer to.
	color[0] = 0;
	color[1] = 0;
	color[2] = 0;
	color[3] = 1.f;

	mDeviceContext->OMSetRenderTargets(1, &mRenderTargetView, mStencilViewDepthBuffer);
	mDeviceContext->RSSetViewports(1, &mViewportShadow);
	mDeviceContext->ClearRenderTargetView(mRenderTargetView, color);
	mDeviceContext->ClearDepthStencilView(mStencilViewDepthBuffer, D3D11_CLEAR_DEPTH, 1.0f, 0);

	Game::Instance()->GetMainRenderItemManager()->DepthRender(pViewMatrix, pProjectionMatrix);
}

ID3D11ShaderResourceView* ShadowMap::GetTexture()
{
	return mTextureRessource;
}



void ShadowMap::CreateTexture()
{
	HRESULT result;

	D3D11_TEXTURE2D_DESC sTexDesc;
	sTexDesc.Width = mWidth;
	sTexDesc.Height = mHeight;
	sTexDesc.MipLevels = 1;
	sTexDesc.ArraySize = 1;
	sTexDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
	sTexDesc.SampleDesc.Count = 1;
	sTexDesc.SampleDesc.Quality = 0;
	sTexDesc.Usage = D3D11_USAGE_DEFAULT;
	sTexDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
	sTexDesc.CPUAccessFlags = 0;
	sTexDesc.MiscFlags = 0;

	result = mDevice->CreateTexture2D(&sTexDesc,NULL, &mTexture);
	if(FAILED(result))
	{
		return;
	}
}